package com.example.viewtest.draw_6;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.example.viewtest.R;
import com.example.viewtest.Utils;

/**
 * 圆形头像
 */
public class HeadPhotoView extends View {
    private static final float PAINDING = Utils.db2px(20);
    private static final float FRAME_WIDTH = Utils.db2px(10);

    private RectF rectF = new RectF();
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);

    public HeadPhotoView(Context context) {
        super(context);
    }

    public HeadPhotoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HeadPhotoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        rectF.set(0, 0, getMeasuredWidth(), getMeasuredWidth());
    }

    {
        paint.setColor(Color.GRAY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float radius = rectF.width() / 2 - PAINDING;
        canvas.drawCircle(rectF.centerX(), rectF.centerY(), radius, paint);

        int i = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);
        canvas.drawCircle(rectF.centerX(), rectF.centerY(), radius - FRAME_WIDTH * 2, paint);
        paint.setXfermode(xfermode);
        canvas.drawBitmap(getBitmap((int) (getWidth() - FRAME_WIDTH * 2)), FRAME_WIDTH, FRAME_WIDTH, paint);
        paint.setXfermode(null);
        canvas.restoreToCount(i);

    }

    private Bitmap getBitmap(int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), R.mipmap.head, options);
        options.inJustDecodeBounds = false;

        options.inDensity = options.outWidth;
        options.inTargetDensity = width;

        return BitmapFactory.decodeResource(getResources(), R.mipmap.head, options);
    }
}
